package com.yuanxin.networking;

import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import top.zibin.luban.Luban;

/**
 * Created by lemon on 2016/12/19.
 */

public class YuanXinNetWorkModule extends ReactContextBaseJavaModule {
    public YuanXinNetWorkModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    /**
     * @return the name of this module. This will be the name used to {@code require()} this module
     * from javascript.
     */
    @Override
    public String getName() {
        return "YuanXinNetworkingManager";
    }

    @ReactMethod
    public void putFile(ReadableMap fileInfo, final Promise promise) {

        Log.e("TAG", "putFile---" + fileInfo);
        String urlString = BuildConfig.PlatformAddress + "FileUploadService/api/upload";
        String filePath = fileInfo.getString("filePath");

        String bucketName = null;
        String resourceID = null;
        String storageType = null;
        String objectKey = null;

        if (fileInfo.hasKey("urlString"))
            urlString = fileInfo.getString("urlString");
        if (fileInfo.hasKey("bucketName"))
            bucketName = fileInfo.getString("bucketName");
        if (fileInfo.hasKey("resourceID"))
            resourceID = fileInfo.getString("resourceID");
        if (fileInfo.hasKey("storageType"))
            storageType = fileInfo.getString("storageType");
        if (fileInfo.hasKey("objectKey"))
            objectKey = fileInfo.getString("objectKey");
        if (objectKey == null || "".equals(objectKey))
            objectKey = java.util.UUID.randomUUID().toString().replace("-", "");

        FileInfoBean fileInfoBean = null;
        try {
            List<File> list = Luban.with(getCurrentActivity()).ignoreBy(5000).load(filePath).get();
            if (list != null && list.size() > 0) {
                fileInfoBean = new FileInfoBean(filePath, LocalUtil.file2byte(list.get(0)), objectKey);
            } else {
                promise.reject("error", "file compress fail");
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String suffixName = fileInfoBean.getFormatPath().substring(fileInfoBean.getFormatPath().lastIndexOf('.'));//取出文件的后缀名  .png   .jpg

        String fileName = fileInfoBean.getObjectKey() + suffixName;//objectKey  就是服务器上的文件名     .jpg


        OkGo.<String>post(urlString)
                .params(fileInfoBean.getObjectKey(),
                        LocalUtil.byte2File(fileInfoBean.getFileByte(), fileInfoBean.getFormatPath(), fileName),
                        fileName, MediaType.parse(LocalUtil.guessMimeType(fileName)))
                .params("bucketName", bucketName)
                .params("resourceID", resourceID)
                .params("storageType", storageType)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        // Log.i("NewWorking", "onResponse===>" + response.body());
                        WritableArray writableArray = Arguments.createArray();
                        try {
                            JSONArray result = new JSONArray(response.body());
                            for (int k = 0; k < result.length(); k++)
                                writableArray.pushString(result.getString(k));
                        } catch (JSONException ex) {
                            promise.reject(ex.getLocalizedMessage(), ex);
                        }
                        promise.resolve(writableArray);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        promise.reject(response.getException().getLocalizedMessage(), response.getException());
                    }
                });

    }


    @ReactMethod
    public void uploadFiles(ReadableMap fileInfo, final Promise promise) {
        String resourceID = java.util.UUID.randomUUID().toString().replace("-", "");
        String storageType = "0";

        String urlString = BuildConfig.PlatformAddress + "FileUploadService/api/upload";
        String bucket = "Office";
        if (fileInfo.hasKey("resourceID"))
            resourceID = fileInfo.getString("resourceID");
        if (fileInfo.hasKey("storageType"))
            storageType = String.valueOf(fileInfo.getInt("storageType"));
        if (fileInfo.hasKey("urlString"))
            urlString = fileInfo.getString("urlString");
        if (fileInfo.hasKey("bucket"))
            bucket = fileInfo.getString("bucket");

        PostRequest<String> postRequest = OkGo.<String>post(urlString)
                .params("bucketName", bucket)
                .params("resourceID", resourceID)
                .params("storageType", storageType);

        ReadableArray fileList = fileInfo.getArray("files");
        for (int i = 0; i < fileList.size(); i++) {
            ReadableMap fileItem = fileList.getMap(i);
            String filePath = fileItem.getString("filePath");
            String objectKey = "";

            if (fileItem.hasKey("objectKey"))
                objectKey = fileItem.getString("objectKey");
            if (objectKey == null || "".equals(objectKey))
                objectKey = java.util.UUID.randomUUID().toString().replace("-", "");

            FileInfoBean fileInfoBean = null;
            try {
                List<File> list = Luban.with(getCurrentActivity()).ignoreBy(5000).load(filePath).get();
                if (list != null && list.size() > 0) {
                    fileInfoBean = new FileInfoBean(filePath, LocalUtil.file2byte(list.get(0)), objectKey);
                } else {
                    promise.reject("error", "file compress fail");
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
//            Log.e(getName(),"=="+fileInfoBean.toString());
            String suffixName = fileInfoBean.getFormatPath().substring(fileInfoBean.getFormatPath().lastIndexOf('.'));//取出文件的后缀名  .png   .jpg

            String fileName = fileInfoBean.getObjectKey() + suffixName;//objectKey  就是服务器上的文件名     .jpg
//            Log.e(getName(),"=="+fileInfoBean.toString());
//            Log.e(getName(),"=="+fileInfoBean.getFormatPath());
//            Log.e(getName(),"=="+fileName);
            String filePathString=fileInfoBean.getFilePath().substring(0,fileInfoBean.getFilePath().lastIndexOf("/"));
//            Log.e(getName(),"=="+filePathString);
            postRequest.params(fileInfoBean.getObjectKey(),
                    LocalUtil.byte2File(fileInfoBean.getFileByte(), filePathString, fileName),
                    fileName, MediaType.parse(LocalUtil.guessMimeType(fileName)));
        }

        postRequest.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                // Log.i("NewWorking", "onResponse===>" + response.body());
                WritableArray writableArray = Arguments.createArray();
                try {
                    JSONArray result = new JSONArray(response.body());
                    for (int k = 0; k < result.length(); k++)
                        writableArray.pushString(result.getString(k));
                } catch (Exception ex) {
                    promise.reject(ex.getLocalizedMessage(), ex);
                }
                promise.resolve(writableArray);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                promise.reject(response.getException().getLocalizedMessage(), response.getException());
            }
        });
    }
}
